//package com.yingxue.lesson.service.impl;
//
//import cn.hutool.core.util.RandomUtil;
//import com.sun.org.apache.xpath.internal.operations.String;
//import com.yingxue.lesson.entity.SysFile;
//import com.yingxue.lesson.exception.BusinessException;
//import com.yingxue.lesson.exception.code.BaseResponseCode;
//import com.yingxue.lesson.mapper.SysFileMapper;
//import com.yingxue.lesson.service.FileService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Service;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.ServletOutputStream;
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.IOException;
//import java.io.UnsupportedEncodingException;
//import java.util.Date;
//
//@Service
//@Slf4j
//public class FileServiceImpl implements FileService {
//
//    @Value("${file.path}")
//    private String FILE_PATH;
//    @Value("${file.base-url}")
//    private String fileUrl;
//
//    @Autowired
//    private SysFileMapper sysFileMapper;
//
//    /**
//     * 文件上传
//     */
//    @Override
//    public String upload(MultipartFile file, String userId, Integer type) {
//        //1.定义上传文件名
//        String originalFilename = file.getOriginalFilename();
//        String extensionName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
//        String fileId = RandomUtil.randomUUID();
//        String fileName = fileId+"."+extensionName;
//
//        //2.创建文件路径
//        File filePath = new File(FILE_PATH+fileName);
//        if (!filePath.getParentFile().exists()){
//            filePath.getParentFile().mkdirs();
//        }
//        //3.上传文件
//        try {
//            file.transferTo(filePath);
//            log.info("上传后文件路径:{}",fileUrl);
//            //4.保存文件到 DB
//            //封装SysFile
//            SysFile sysFile = new SysFile();
//            sysFile.setId(RandomUtil.randomString(10));
//            sysFile.setFileName(fileName);
//            sysFile.setCreateTime(new Date());
//            sysFile.setCreateId(userId);
//            sysFile.setExtensionName(extensionName);
//            sysFile.setOriginalName(originalFilename);
//            sysFile.setSize(FileUtils.byteCountToDisplaySize(file.getSize()));
//            sysFile.setFileUrl(fileUrl+fileName);
//            sysFile.setType(type);
//            int i = sysFileMapper.insertSelective(sysFile);
//            if (i!=1){
//                throw new BusinessException(BaseResponseCode.DATA_ERROR);
//            }
//            return "上传成功";
//        } catch (IOException e) {
//            e.printStackTrace();
//            log.error("e:{}",e);
//            throw new BusinessException(BaseResponseCode.UPLOAD_FILE_ERROR);
//        }
//
//    }
//
//    /**
//     * 文件下载
//     */
//    @Override
//    public void download(String fileId, HttpServletResponse response) {
//        //1.根据 fileId 查询文件是否存在
//        SysFile sysFile = sysFileMapper.selectByPrimaryKey(fileId);
//        if (sysFile==null){
//            throw new BusinessException(BaseResponseCode.DATA_ERROR);
//        }
//        //2.定义以流的形式下载
//        try {
//
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            java.lang.String fileName = new java.lang.String(sysFile.getOriginalName().getBytes("UTF-8"), "ISO-8859-1");
//            //3.文件下载响应头的设置
//            response.setHeader("content-disposition", java.lang.String.format("attachment;filename=%s",fileName));
//        } catch (UnsupportedEncodingException e) {
//            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
//        }
//
//        //
//        ServletOutputStream outputStream = null;
//        try {
//            File file = new File(fileUrl + sysFile.getFileName());
//            outputStream = response.getOutputStream();
//            //4.写入文件
//            IOUtils.write(FileUtils.readFileToByteArray(file),outputStream);
//        } catch (IOException e) {
//            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
//        } finally {
//            if (outputStream!=null){
//                try {
//                    outputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
//
//}

package com.yingxue.lesson.service.impl;


import com.github.pagehelper.PageHelper;
import com.yingxue.lesson.entity.SysFile;
import com.yingxue.lesson.exception.BusinessException;
import com.yingxue.lesson.exception.code.BaseResponseCode;
import com.yingxue.lesson.mapper.SysFileMapper;
import com.yingxue.lesson.service.FileService;

import com.yingxue.lesson.utils.PageUtil;
import com.yingxue.lesson.vo.req.fileVo.FilePageReqVO;
import com.yingxue.lesson.vo.resp.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName: FileServiceImpl
 * TODO:类文件简单描述
 * @Author: 小霍
 * @UpdateUser: 小霍
 * @Version: 0.0.1
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Value("${file.path}")
    private String FILE_PATH;
    @Value("${file.base-url}")
    private String baseUrl;
    @Autowired
    private SysFileMapper sysFileMapper;
    @Override
    public String upload(MultipartFile file, String userId, Integer type) {
        String originalFilename = file.getOriginalFilename();
        String extensionName=originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();
        String fileId= UUID.randomUUID().toString();
        String fileName=fileId+"."+extensionName;
        File destFile=new File(FILE_PATH+fileName);
        if(!destFile.getParentFile().exists()){
            destFile.getParentFile().mkdirs();
        }
        String fileUrl=baseUrl+fileName;
        try {

            log.info("baseUrl:{}",fileUrl);
            file.transferTo(destFile);
            SysFile sysFile=new SysFile();
            sysFile.setId(UUID.randomUUID().toString());
            sysFile.setFileName(fileName);
            sysFile.setOriginalName(originalFilename);
            sysFile.setExtensionName(extensionName);
            sysFile.setCreateId(userId);
            sysFile.setType(type);
            sysFile.setFileUrl(fileUrl);
            sysFile.setSize(FileUtils.byteCountToDisplaySize(file.getSize()));
            int i = sysFileMapper.insertSelective(sysFile);
            if(i!=1){
                throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("e:{}",e);
            throw new BusinessException(BaseResponseCode.UPLOAD_FILE_ERROR);
        }
        return fileUrl;
    }

    /**
     * 文件下载
     * @param fileId
     * @param response
     */
    @Override
    public void download(String fileId, HttpServletResponse response) {
        SysFile sysFile = sysFileMapper.selectByPrimaryKey(fileId);
        if(sysFile==null){
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String fileName=new String(sysFile.getOriginalName().getBytes("UTF-8"),"ISO-8859-1");
            response.setHeader("content-disposition",String.format("attachment;filename=%s",fileName));
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
        ServletOutputStream outputStream=null;
        try {
            File file=new File(FILE_PATH+sysFile.getFileName());
            outputStream = response.getOutputStream();
            IOUtils.write(FileUtils.readFileToByteArray(file),outputStream);
        } catch (IOException e) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 根据 fileUrl 删除文件
     */
    @Override
    public int deleteByFileUrl(String fileUrl) {
        //1.删除数据库
        int i = sysFileMapper.deleteByFileUrl(fileUrl);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        deleteRealFile(fileName);
        //2.删除磁盘的文件
        return i;
    }

    /**
     * //2.删除磁盘的文件
     */
    public void deleteRealFile(String fileName){
        File file = new File(FILE_PATH + fileName);
        if (file.exists()){
            file.delete();
        }
    }


    /**
     * 分页查询所有文件
     */
    @Override
    public PageVO<SysFile> pageInfo(FilePageReqVO vo, String userId) {
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<SysFile> sysFiles = sysFileMapper.selectFileByUserId(userId);
        PageVO pageVo = PageUtil.getPageVo(sysFiles);
        return pageVo;
    }
}

